<script lang="ts" setup>
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import { Message, Tooltip } from '@arco-design/web-vue'
import IconsQuestion from '~icons/icons/question'
import { getNodeDetailApi, updateCdnNodeApi } from '@/apis/modules/cdn.ts'
// import { getApiNodeApi, updateApiNodeApi } from '@/apis/modules/node/node'

import {
  capacityOptions,
  diskFileSizeOptions,
  MaxSizeOptions,
  memoryFileSizeOptions,
} from '@/constants/cdn-node'

const loading = ref(false)
const route = useRoute()

const formState = reactive({
  // cache_path: '',
  // cache_size: 0,
  // index_size: 0,
  disk_configs: [
    {
      path: '',
      capacity: {
        value: 200,
        unit: 3,
      },
    },
  ],
  disk_single_file_limit: {
    value: 200,
    unit: 2,
  },
  memory_config: {
    mode: 1,
    max_capacity: {
      value: 1,
      unit: 2,
    },
    single_file_limit: {
      value: 4,
      unit: 2,
    },
  },
})

// const unit = ref(2)
// const index_unit = ref(2)
// const originData = ref()

const formRef = ref<FormInstance>()
const nodeId = computed(() => route.params.id as string)
const rules = computed<Record<string, FieldRule>>(() => {
  return {
    // cache_path: {
    //   required: true,
    //   validator(value, callback) {
    //     // const reg = /^\/(?:[^/]+(\/)?)*$/
    //     const reg = /^\/[^/]*(?:\/[^/]*)*$/
    //     // const reg = /^$/
    //     if (!value) {
    //       return callback('缓存目录不能为空')
    //     }
    //     if (!reg.test(value)) {
    //       return callback('路缓存目录不正确')
    //     }
    //     callback()
    //   },
    // },
    // index_size: indexSizeRule(index_unit.value),
    // cache_size: cacheSizeRule(unit.value),
    // cacheSizeRule(unit.value),
    // 磁盘-单文件最大大小
    // 'disk_single_file_limit.value': fileSizeRule(
    //   diskFileSizeOptions,
    //   formState.disk_single_file_limit.unit,
    //   '请输入单文件最大大小',
    // ),
    // // 内存-单文件最大大小
    // 'memory_config.single_file_limit.value': fileSizeRule(
    //   memoryFileSizeOptions,
    //   formState.memory_config.single_file_limit.unit,
    //   '请输入单文件最大大小',
    // ),
    // // 内存-最大容量
    // 'memory_config.max_capacity.value': {
    //   required: false,
    //   validator(value, callback) {
    //     const max = getOptionsLabel(
    //       MaxSizeOptions,
    //       formState.memory_config.max_capacity.unit,
    //       'max',
    //     )
    //     if (formState.memory_config.mode !== 2) {
    //       // 模式不是2，不需要验证
    //       callback()
    //       return
    //     }
    //     if (!value) {
    //       return callback('请输入最大容量')
    //     }
    //     if (value > Number(max)) {
    //       return callback(`最大值为${max}`)
    //     }
    //     return callback()
    //   },
    // },
  }
})
const nodeName = ref('')
function getNodeInfo() {
  // 获取节点信息
  getNodeDetailApi({ id: nodeId.value }).then((res) => {
    const node = res.node!
    // originData.value = cloneDeep(res)
    // const size = res.cache_size ?? '0GB'
    // const index_size = res.index_size ?? '0GB'
    // const { value, unit: symbol } = separateNumberAndLetter(size)
    // const { value: index_value, unit: index_symbol }
    //   = separateNumberAndLetter(index_size)
    // formState.cache_path = res.cache_path ?? ''
    // formState.cache_size = Number(value)
    // formState.index_size = Number(index_value)
    // const index = diskOptions.find(item => item.label === symbol)
    //   ?.value as number
    // unit.value = index ?? 2
    const disk_configs = (node.disk_configs ?? []).map(item => ({
      ...item,
      capacity: {
        ...item.capacity,
        value: Number(item.capacity.value) || 0,
      },
    }))
    nodeName.value = node.name
    formState.disk_configs = disk_configs
    formState.disk_single_file_limit = {
      ...node.disk_single_file_limit,
      value: Number(node.disk_single_file_limit.value) || 0,
    }
    formState.memory_config = {
      ...node.memory_config,
      max_capacity: {
        ...node.memory_config.max_capacity,
        value: Number(node.memory_config.max_capacity.value) || 0,
      },
      single_file_limit: {
        ...node.memory_config.single_file_limit,
        value: Number(node.memory_config.single_file_limit.value) || 0,
      },
    }
  })
}

function handleTableCommand(command: string, index?: number) {
  const map: Record<string, any> = {
    add: () => {
      formState.disk_configs.push({
        path: '',
        capacity: {
          value: 200,
          unit: 3,
        },
      })
    },
    delete: () => {
      formState.disk_configs!.splice(index!, 1)
    },
  }
  map[command] && map[command]()
}

// 检验目录是否重复
function hasDuplicates(arr) {
  return new Set(arr).size !== arr.length
}

async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error)
    return
  // const symbol = diskOptions.find(item => item.value === unit.value)?.label
  // const index_symbol = indexSizeOptions.find(
  //   item => item.value === index_unit.value,
  // )?.label
  if (hasDuplicates(formState.disk_configs.map(item => item.path))) {
    Message.error('存储目录不能重复')
    return false
  }
  const data = {
    id: nodeId.value,
    ...formState,
    // cache_path: formState.cache_path,
    // cache_size: `${formState.cache_size}${symbol}`,
    // index_size: `${formState.index_size}${index_symbol}`,
  }

  loading.value = true
  const fn = async () =>
    await updateCdnNodeApi(data)
      .then(() => {
        Message.success('操作成功')
        loading.value = false
        getNodeInfo()
      })
      .catch(() => (loading.value = false))
  fn()
  // if (
  //   data.cache_path !== originData.value?.cache_path
  //   || data.index_size !== originData.value?.index_size
  // ) {
  //   ModalHelper.error(
  //     {
  //       content: '修改缓存路径或磁盘空间需要重启节点，确认继续？',
  //     },
  //     fn,
  //   )
  // } else {
  //   fn()
  // }
}

const tableColumn = buildColumns([
  // {
  //   title: '存储目录',
  //   slotName: 'ip',
  // },
  {
    title: () =>
      h('div', { class: 'flex gap-x-1 items-center' }, [
        h('span', { class: 'text-12px/22px' }, '存储目录'),
        h('span', { class: 'text-12px text-[#FA5566]' }, ' *'),
        h(
          Tooltip,
          {
            showArrow: false,
            class: 'border-radius-20px',
            contentStyle: {
              borderRadius: '12px !important',
            },
          },
          {
            default: () =>
              h(IconsQuestion, {
                class:
                  'question-icon text-#8F959E w-14px  h-14px hover:text-primary',
              }),
            content: () =>
              h(
                'span',
                {
                  class: 'text-12px',
                },
                [
                  '用于持久化缓存的磁盘存储目录（需设置目录所有者权限为 nobody）。',
                ],
              ),
          },
        ),
      ]),
    slotName: 'path',
    // render({ record }) {
    //   return record.cascade_level === 1 ? 'L1' : 'L2'
    // },
  },
  {
    title: () =>
      h('div', { class: 'flex gap-x-1 items-center' }, [
        h('span', { class: 'text-12px/22px' }, '分配容量'),
        h('span', { class: 'text-12px text-[#FA5566]' }, ' *'),
        h(
          Tooltip,
          {
            showArrow: false,
            class: 'border-radius-20px',
            contentStyle: {
              borderRadius: '12px !important',
            },
          },
          {
            default: () =>
              h(IconsQuestion, {
                class:
                  'question-icon text-#8F959E w-14px  h-14px hover:text-primary',
              }),
            content: () =>
              h(
                'span',
                {
                  class: 'text-12px',
                },
                ['为存储目录分配的存储容量。'],
              ),
          },
        ),
      ]),
    slotName: 'capacity',
    width: 160,
    // render({ record }) {
    //   return record.cascade_level === 1 ? 'L1' : 'L2'
    // },
  },
  {
    title: '操作',
    slotName: 'action',
    cellClass: 'actions-cell',
    width: 56,
  },
])
// 磁盘列表-存储目录
const catalogueRules: FieldRule = {
  required: true,
  validator: (value, callback) => {
    if (!value) {
      return callback('存储目录不能为空')
    }
    // if (!regexpMap.ipv4.test(value)) {
    //   return callback('存储目录格式不正确')
    // }
    callback()
  },
}
// 磁盘列表-分配容量
const sizeRules: FieldRule = {
  required: true,
  validator(value, callback) {
    // const max = getOptionsLabel(capacityOptions, unit, 'max')
    if (!value) {
      return callback('分配容量不能为空')
    }
    if (value > 999) {
      return callback(`最大值为999`)
    }
    callback()
  },
}

// 磁盘-单文件最大大小
const diskSingleFileLimitRules: FieldRule = {
  required: true,
  validator: (value, callback) => {
    const max = getOptionsLabel(
      diskFileSizeOptions,
      formState.disk_single_file_limit.unit,
      'max',
    )
    if (!value) {
      return callback('请输入单文件最大大小')
    }
    if (value > Number(max)) {
      return callback(`最大值为${max}`)
    }
    return callback()
  },
}

// 内存-单文件最大大小
const singleFileLimitRules: FieldRule = {
  required: true,
  validator: (value, callback) => {
    const max = getOptionsLabel(
      memoryFileSizeOptions,
      formState.memory_config.single_file_limit.unit,
      'max',
    )
    if (!value) {
      return callback('请输入单文件最大大小')
    }
    if (value > Number(max)) {
      return callback(`最大值为${max}`)
    }
    return callback()
  },
}

// 内存-最大容量
const singleMaxCapacityRules: FieldRule = {
  // required: formState.memory_config.mode === 2, // 只在手动模式下必填
  required: true,
  validator: (value, callback) => {
    if (formState.memory_config.mode !== 2) {
      return callback() // 非手动模式不验证
    }

    if (!value) {
      return callback('请输入最大容量')
    }

    const currentUnit = formState.memory_config.max_capacity.unit
    const max = getOptionsLabel(MaxSizeOptions, currentUnit, 'max')
    if (value > max) {
      return callback(`最大值为${max}`)
    }

    return callback()
  },
}

watchEffect(() => {
  getNodeInfo()
})
</script>

<template>
  <main-container
    :show-pagination="false"
    inner
  >
    <template #title>
      <a-breadcrumb class="main-container__breadcrumb">
        <a-breadcrumb-item>
          <router-link :to="{ name: 'CdnNodeNodeList' }">
            节点列表
          </router-link>
        </a-breadcrumb-item>
        <a-breadcrumb-item class="text-12px">
          {{ nodeName }}
        </a-breadcrumb-item>
      </a-breadcrumb>
    </template>
    <div class="mt-24px" />
    <div
      style="height: calc(100vh - 240px); overflow: auto"
      class="mt-2"
    >
      <div class="h-full">
        <a-form
          ref="formRef"
          layout="vertical"
          :model="formState"
          :rules="rules"
          class="w-100!"
        >
          <div class="node-sub-title mb-4">
            磁盘配置
          </div>
          <a-form-item
            label=""
            field=""
            asterisk-position="end"
          >
            <a-table
              :columns="tableColumn"
              :data="formState.disk_configs"
              class="node-ip-table"
              :pagination="false"
            >
              <template #path="{ record, rowIndex }">
                <a-form-item
                  :field="`disk_configs[${rowIndex}].path`"
                  hide-asterisk
                  hide-label
                  :rules="catalogueRules"
                  validate-trigger="blur"
                >
                  <a-input
                    v-model="record.path"
                    placeholder="请输入存储目录"
                  />
                </a-form-item>
              </template>
              <template #capacity="{ record, rowIndex }">
                <a-form-item
                  :field="`disk_configs[${rowIndex}].capacity.value`"
                  hide-asterisk
                  hide-label
                  :rules="sizeRules"
                  validate-trigger="blur"
                >
                  <a-input-number
                    v-model="record.capacity.value"
                    :controls="true"
                    :precision="0"
                    :min="1"
                    :max-length="13"
                    class="cloud-input-number"
                    hide-button
                    placeholder="请输入"
                    :step="1"
                  >
                    <template #append>
                      <a-select
                        v-model="record.capacity.unit"
                        :options="capacityOptions"
                        class="rounded-tl-none rounded-bl-none! border-none! bg-transparent!"
                      />
                    </template>
                  </a-input-number>
                </a-form-item>
              </template>
              <template #action="{ rowIndex }">
                <a-link
                  :hoverable="false"
                  status="danger"
                  :disabled="formState.disk_configs.length <= 1"
                  @click="handleTableCommand('delete', rowIndex)"
                >
                  <i-icons-delete size="16px" />
                </a-link>
              </template>
              <template #footer>
                <a-link
                  class="cloud-diverse-select h-[30px] w-fit items-center gap-x-2 !flex"
                  :hoverable="false"
                  @click="handleTableCommand('add')"
                >
                  <i-icons-table-add />
                  添加存储目录
                </a-link>
              </template>
            </a-table>
          </a-form-item>

          <a-form-item
            label="单文件最大大小"
            field="disk_single_file_limit.value"
            hide-asterisk
            asterisk-position="end"
            required
            :rules="diskSingleFileLimitRules"
          >
            <template #label>
              <div class="flex items-center gap-x-1">
                <span>单文件最大大小</span>
                <span class="text-[#FA5566]">*</span>
                <a-tooltip
                  :show-arrow="false"
                  :content-style="{ 'max-width': '509px' }"
                >
                  <i-icons-question class="question-icon" />
                  <template #content>
                    <span>允许存入磁盘缓存的单个文件大小</span>
                  </template>
                </a-tooltip>
              </div>
            </template>
            <a-input-number
              v-model="formState.disk_single_file_limit.value"
              :controls="true"
              :precision="0"
              :min="1"
              :max-length="13"
              class="cloud-input-number"
              hide-button
              placeholder="请输入单文件最大大小"
            >
              <template #append>
                <a-select
                  v-model="formState.disk_single_file_limit.unit"
                  :options="diskFileSizeOptions"
                  class="rounded-tl-none rounded-bl-none! border-none! bg-transparent!"
                />
              </template>
            </a-input-number>
            <!-- <a-input-number v-model="formData.cache_size" :max-length="13" class="!w-100"  placeholder="请输入缓存最大容量">
            <template #append>
              <a-select v-model="diskFileSizeUnit" :options="diskOptions">
              </a-select>
            </template>
          </a-input-number> -->
          </a-form-item>

          <a-divider
            type="dashed"
            margin="0"
          />
          <div class="node-sub-title mb-4 mt-6">
            内存配置
          </div>

          <a-form-item
            label="最大容量"
            hide-asterisk
            field="memory_config.max_capacity.value"
            :rules="singleMaxCapacityRules"
          >
            <template #label>
              <div class="flex items-center gap-x-1">
                <span>最大容量</span>
                <span class="text-[#FA5566]">*</span>
                <a-tooltip
                  :content-style="{ 'max-width': '509px' }"
                  :show-arrow="false"
                >
                  <i-icons-question class="question-icon text-#86909C" />
                  <template #content>
                    <span>
                      1.智能分配：根据磁盘已分配的总容量，按最优比例自动计算并分配内存（约10MB
                      RAM / 1GB 磁盘）。
                      <br>
                      2.手动分配：为内存指定固定容量。
                    </span>
                  </template>
                </a-tooltip>
              </div>
            </template>
            <div class="w-full">
              <div class="h-8">
                <a-radio-group
                  v-model="formState.memory_config.mode"
                  class="ml-2"
                >
                  <a-radio :value="1">
                    智能分配
                  </a-radio>
                  <a-radio :value="2">
                    手动分配
                  </a-radio>
                </a-radio-group>
              </div>

              <div v-if="formState.memory_config.mode === 2">
                <a-input-number
                  v-model="formState.memory_config.max_capacity.value"
                  :controls="true"
                  :precision="0"
                  :min="1"
                  :max-length="13"
                  class="cloud-input-number"
                  hide-button
                  placeholder="请输入最大容量"
                >
                  <template #append>
                    <a-select
                      v-model="formState.memory_config.max_capacity.unit"
                      :options="MaxSizeOptions"
                      class="rounded-tl-none rounded-bl-none! border-none! bg-transparent!"
                    />
                  </template>
                </a-input-number>
              </div>
            </div>
          </a-form-item>

          <a-form-item
            label="单文件最大大小"
            field="memory_config.single_file_limit.value"
            hide-asterisk
            asterisk-position="end"
            required
            :rules="singleFileLimitRules"
          >
            <template #label>
              <div class="flex items-center gap-x-1">
                <span>单文件最大大小</span>
                <span class="text-[#FA5566]">*</span>
                <a-tooltip
                  :show-arrow="false"
                  :content-style="{ 'max-width': '509px' }"
                >
                  <i-icons-question class="question-icon" />
                  <template #content>
                    <span>允许存入内存缓存的单个文件大小。</span>
                  </template>
                </a-tooltip>
              </div>
            </template>
            <a-input-number
              v-model="formState.memory_config.single_file_limit.value"
              :controls="true"
              :precision="0"
              :min="1"
              :max-length="13"
              class="cloud-input-number"
              hide-button
              placeholder="请输入单文件最大大小"
            >
              <template #append>
                <a-select
                  v-model="formState.memory_config.single_file_limit.unit"
                  :options="memoryFileSizeOptions"
                  class="rounded-tl-none rounded-bl-none! border-none! bg-transparent!"
                />
              </template>
            </a-input-number>
            <!-- <a-input-number v-model="formData.cache_size" :max-length="13" class="!w-100"  placeholder="请输入缓存最大容量">
            <template #append>
              <a-select v-model="diskFileSizeUnit" :options="diskOptions">
              </a-select>
            </template>
          </a-input-number> -->
          </a-form-item>

          <a-form-item>
            <a-button
              type="primary"
              :loading="loading"
              @click="handleSubmit"
            >
              保存并重启
            </a-button>
          </a-form-item>
        </a-form>
      </div>
    </div>
  </main-container>
</template>

<style lang="less" scoped>
.arco-form {
  .path-item:deep(.arco-form-item-label) {
    display: flex;
    width: 100%;
    .arco-form-item-label-required-symbol {
      position: relative;
    }
  }
  .question-icon {
    color: #86909c;
    width: 14px !important;
    height: 14px !important;
    cursor: pointer;

    &:hover {
      color: #00a65b;
    }
  }
  :deep(.arco-input-append) {
    background-color: #ffffff;
  }
}

.node-sub-title {
  color: var(--text-1, #1d2129);
  font-size: 12px;
  font-style: normal;
  font-weight: 700;
  line-height: normal;
}

.node-ip-table {
  //border: 1px solid #dfe2e5;
  //@apply rounded-2 overflow-hidden;

  :deep(.arco-table-container) {
    border-radius: 8px 8px 0px 0px !important;
  }

  :deep(.arco-table-tr) {
    @apply !bg-#fff;
  }

  :deep(.arco-table-th) {
    @apply !bg-transparent;
  }

  :deep(.arco-table-footer) {
    //border-width: 0px !important;
    border-radius: 0px 0px 8px 8px !important;
    border: 1px solid #f0f5f5;
    border-top: none;
  }
}
</style>
